<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/2/19
  Time: 9:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>

    <link rel="stylesheet" href="./css/leaflet.css" />
    <link rel="stylesheet" type="text/css" href="./easyui/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="./easyui/icon.css">
    <link rel="stylesheet" type="text/css" href="./easyui/color.css">
    <script type="text/javascript" src="./js/jquery.min.js"></script>
    <script  src="./js/jquery.easyui.min.js"></script>
    <script src="./js/leaflet.js"></script>
    <script src="./js/CustomWebSDK.min.js"></script>
    <script src="./js/server-root.js"></script>
    <script src="./js/leaflet.rotatedMarker.js"></script>

    <style>
        #map { width: 100%; height: 100%; }
        body { width: 100%; height: 100%;margin: 0px;font: 16px/1.4 "Helvetica Neue", Arial, sans-serif; }
        #beginDate{padding-top: 60px }
        #mm { width:270px!important;height:220px;padding:10px;border-radius: 10px;position:fixed ; right: 100px;top:20px;z-index: 500; position: absolute}
        #play { margin:80px 0;margin: 5px ; background-color: white}

    </style>
</head>


<body >

<div id="mm" class="easyui-panel"  >
    <h3 align="center">轨迹查询</h3>

    开始日期 : <input class="easyui-datetimebox" name="begindate" id="beginDate" data-options="formatter:myformatter,parser:myparser" ></input>
    <br>
    <br>
    结束日期  : <input class="easyui-datetimebox" name="enddate" id="endDate" data-options="formatter:myformatter,parser:myparser"></input>
    <!--<div style="text-align:center;padding:5px">-->
    <!--<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">提交</a>-->
    <!--<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()">清除</a>-->

    <!--</div>-->
    <br>
    <br>
    出租车车牌号: <input id="inputText" class="easyui-textbox" data-options="buttonText:'搜索',prompt:'请输入车牌号...'" style="width:150px;height:32px;" onClickButton="submitForm()">

    <div id="play">
        <button onclick="runMoveCar()" >开始</button>
        <button onclick="runMoveCar() " >重新开始</button>
        <button onclick="pauseCar()" >暂停</button>
        <button onclick="continueCar()" >继续</button>
    </div>


</div>



<div id="map"></div>

<script src="./js/leaflet-heat.js"></script>
<script>

    var map = L.map('map',{crs:L.CRS.CustomEPSG4326,center: {lon:116.4, lat:39.93},zoom: 11,inertiaDeceleration:15000});
    var polyline = null;

    L.tileLayer('http://t4.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=42cac6e13cafbf0ee8d55b2f7af43dc8', {}).addTo(map);
    L.tileLayer('http://t1.tianditu.com/DataServer?T=cva_c&x={x}&y={y}&l={z}&tk=42cac6e13cafbf0ee8d55b2f7af43dc8', {}).addTo(map);

    var heatLayer;


    var latlngs = [];
    var marker = null;


    map.on('moveend', function(e) {
        updateHeatMap();
    });

    map.on('resize', function(e) {
        updateHeatMap();
    });

    updateHeatMap();
    setInterval(updateHeatMap,10000);

    $('#play').hide()

    function updateHeatMap(){
        var bounds = map.getBounds();
        var boundsStr =  bounds._southWest.lng+','+bounds._southWest.lat+','+bounds._northEast.lng+','+bounds._northEast.lat;
        var zoom = map.getZoom();
//        date.setMonth(date.getMonth()+1)
        var date = new Date();;
        date.setDate(date.getDay()+2);
//        var time = date.Format("yyyy-MM-dd hh:mm:ss");
        var time ='2008-02-02 15:50:00';
        var addressPoints = [];
        var url = server_root+'/mongo/taxiHotMap?{data:{bbox:['+boundsStr+'];level:'+zoom+';time:"'+time+'"}}&tk=42cac6e13cafbf0ee8d55b2f7af43dc8';
        $.ajax(url,{dataType:'json',success:function(data){
            data = data.data;
            for(var i = 0;i<data.length;i++){
                var item = data[i];
//                var bbox = item.bbox;
//                var d1 = (bbox[1]-bbox[3])*0.5;
//                var d2 = (bbox[2]-bbox[0])*0.5;
//                var p1 = parseFloat(bbox[3])+d1;
//                var p2 =parseFloat(bbox[0])+d2;
                var p1 = item.cp[1];
                var p2 = item.cp[0];
                var p3 = item.count;
                if(!p3){
                    p3=1;
                }
                addressPoints.push([p1,p2,p3]);
            }

            if(!heatLayer){
                heatLayer = L.heatLayer([],{radius: 25});
                map.addLayer(heatLayer);
            }
            heatLayer.setLatLngs(addressPoints);
        }});
    }


    function myformatter(date) {

        var y = date.getFullYear();

        var m = date.getMonth() + 1;

        var d = date.getDate();

        var h = date.getHours();

        var min = date.getMinutes();

        var s = date.getSeconds();

        return y + '-' + (m < 10 ? ('0' + m) : m) + '-'

            + (d < 10 ? ('0' + d) : d) +' '+(h < 10 ? ('0' + h) : h)+':'+(min < 10 ? ('0' + min) : min)+':'+(s < 10 ? ('0' + s) : s) ;
    }

    function myparser(s) {

        if (!s)

            return new Date();

        var ss = (s.split(' '));

        var day = ss[0].split('-');

        var ms = ss[1].split(':');

        var y = parseInt(day[0], 10);

        var m = parseInt(day[1], 10);

        var d = parseInt(day[2], 10);

        var h = parseInt(ms[0],10);

        var min = parseInt(ms[1],10);

        var s = parseInt( ms[2],10);

        if (!isNaN(y) && !isNaN(m) && !isNaN(d)&& !isNaN(h)&& !isNaN(min)&& !isNaN(s)) {

            return new Date(y, m - 1, d,h,min,s);

        } else {

            return new Date();

        }
    }

    $(document).ready(function(){
        init();
    });

    function init(){
        $('#inputText').textbox({
            onClickButton: function(){
                var taxiNum = $('#inputText').val();
                var beginDate = $('#beginDate').datebox('getValue');
                var endDate = $('#endDate').datebox('getValue');
                sendRequest(taxiNum,beginDate,endDate);

                $('#play').show();
            }
        });
    }


    function sendRequest(taxiNum,beginDate,endDate){
        var url =  'http://172.16.6.104:8201/mongo'+'/mongo/taxiTrack?{data:{taxi_num:';
        url = url + taxiNum+',startTime:"'+beginDate+'",endTime:"'+endDate+'"}}';
        $.ajax({
            url:url,
            dataType:"json",
            success: function (result) {
                //地图上划线
                var strJSON = result;//得到的JSON

                for(var i = 0;i<result.data.length;i++){//获取全部的数据
                    var item = result.data[i];
                    var itemArr = [];
                    itemArr.push(item.y);
                    itemArr.push(item.x);
                    latlngs.push(itemArr);
                }


                /* if( L.marker){
                 map.removeLayer(c);
                 }*/
                if(polyline){
                    map.removeLayer(polyline);
                }//

                polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
                // 把地图放大到折线
                map.fitBounds(polyline.getBounds());

                var myIcon = L.icon({
                    iconUrl: 'slune.png',
                    iconSize: [40, 40],
                    iconAnchor:[20,20]
                });

                marker = L.marker(latlngs[0], {icon: myIcon,rotationAngle: 0});

                marker.addTo(map);
            },
            fail:function(e){
                //给出输入值错误
                alert("您输入的值错误！！")

            },
        })
    }


    var time = 3000;
    var lineIndex = 0;//两点之间的线段索引
    var count = 0;
    var lineCount = 0;

    var frameId = null;

    function moveCar(){
        lineCount++;
        count++;
        //取两个点，计算两点之间的距离
        var firstPoint = latlngs[lineIndex];
        var sendPoint = latlngs[lineIndex+1];
        var totalDis = getDistance(firstPoint,sendPoint);
        //计算旋转角度
        var angle = getAngle(firstPoint,sendPoint);

        //计算每帧应该运动的距离\
        var dis = totalDis/(time*24*0.001);

        //计算线段上的x，y
        var p = getPoint(firstPoint,sendPoint,dis*lineCount);

        //更新marker
        updateMarker(p,angle);

        if(count !=0 && count % (time*0.001*24) == 0){
            lineCount = 0;
            lineIndex++;
        }

        //计算出什么时候会结束
        if(count == time*0.001*24*(latlngs.length-1)){
            return;
        }
        //运行下一帧
        frameId = requestAnimationFrame(moveCar);
    };



    //点击按钮启动小车
    function runMoveCar(){
        count = 0;
        lineCount = 0;
        lineIndex = 0;
        cancelAnimationFrame(frameId);//取消一帧，等上一帧运行完了再运行下一帧
        //执行第一帧
        frameId = requestAnimationFrame(moveCar);
    }


    function pauseCar() {
        cancelAnimationFrame(frameId);
    }

    function continueCar(){
        frameId = requestAnimationFrame(moveCar);

    }


    function updateMarker(lnglat,angle){
        //更新坐标
        marker.setLatLng(lnglat);
        //更新旋转角度
        marker.setRotationAngle(angle);
    }

    //获取两点连线与y轴的夹角
    function getAngle( p1,p2){
        var k = (p2[1]-p1[1])/(p2[0]-p1[0]);
        var angle = 360*Math.atan(k)/(2*Math.PI);
        return angle;
    }

    /**
     * 求两点之间的距离
     */
    function getDistance(p1,p2){
        var calX = p2[0] - p1[0];
        var calY = p2[1] - p1[1];
        return Math.pow((calX *calX + calY * calY), 0.5);
    }
    //求线上的坐标
    function getPoint(p1,p2,d){
        var xab = p2[0] - p1[0];
        var yab = p2[1] - p1[1];
        var xd = p2[0];
        var yd = p2[1];
        if(xab == 0){
            if(yab > 0){
                yd = p1[1] + d;
            }else{
                yd = p1[1] - d;
            }
        }else{
            var xbd = Math.sqrt((d * d)/((yab/xab) * (yab/xab) + 1));
            if (xab < 0) {
                xbd = -xbd
            }

            xd = p1[0] + xbd;
            yd = p1[1] + yab / xab * xbd;
        }
        return [xd,yd];
    }

    /* var p = getPoint([0,0],[2,2],1) ;
     console.log(p)*/


</script>
</body>
</html>
